package Thread;

import java.util.Random;
import java.util.concurrent.BlockingDeque;

public class BlockingQueue {
    int[] array = new int[1000];
    private volatile  int head = 0;
    private volatile  int tail = 0;
    private volatile  int size = 0;
    //入队列
    public void put(int val) throws InterruptedException {
        synchronized (this)
        {
            while(size == array.length)
            {
                this.wait();
            }
            array[tail] = val;
            tail = (tail+1)% array.length;
            size++;
            this.notify();
        }

    }

    //出队列
    public int take() throws InterruptedException {
        int ret = 0;
        synchronized (this)
        {
            while(size == 0)
            {
                this.wait();
            }

            ret = array[head];
            head = (head+1)% array.length;
            size--;
            this.notify();
        }

        return ret;
    }
    public synchronized int size()
    {
        return size;
    }
    public static void main(String[] args) throws InterruptedException {
        BlockingQueue queue = new BlockingQueue();
        Random random =new Random();
        Thread producter = new Thread(()->{
           while(true)
           {
               int val = random.nextInt(1000);
               try {
                   queue.put(val);
                   System.out.println("生产元素："+val);
               } catch (InterruptedException e) {
                   e.printStackTrace();
               }
           }
        });

        producter.start();
        Thread consumer = new Thread(()->{
            while(true)
            {
                int val = 0;
                try {
                    val = queue.take();
                    System.out.println("消费元素："+val);
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        consumer.start();

        producter.join();
        consumer.join();
    }
}
